package com.golddaymicromall.activity.jifen;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.activity.jifenconfirmpay.BonusPointsConfirmPayActivity;
import com.golddaymicromall.activity.panicbuying.PanicBuyingContract;
import com.golddaymicromall.activity.panicbuying.PanicBuyingPresenter;
import com.golddaymicromall.activity.panicbuyingconfirmpay.PanicBuyingConfirmPayActivity;
import com.golddaymicromall.adapter.JiFenAdapter;
import com.golddaymicromall.adapter.PanicBuyingAdapter;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.JiFenInfo;
import com.golddaymicromall.bean.PanicBuyingInfo;
import com.golddaymicromall.rxbus.RxBus;
import com.golddaymicromall.util.ActivityController;
import com.golddaymicromall.util.Log;
import com.golddaymicromall.util.SPUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

import static com.google.common.base.Preconditions.checkNotNull;

//1.实现Contract接口
public class JiFenActivity extends BaseActivity implements JiFenContract.View {
    //2.Contract.Presenter类型的声明
    JiFenContract.Presenter mPresenter;
    @Bind(R.id.paincbuying_confirmpay_back)
    LinearLayout paincbuying_confirmpay_back;

    @Bind(R.id.panicbuying_listview)
    ListView panicbuyingListview;
    @Bind(R.id.panicbuying_num)
    TextView panicbuyingNum;
    @Bind(R.id.textView2)
    TextView textView2;
    @Bind(R.id.allPrice)
    TextView mAllPrice;
    @Bind(R.id.allPoints)
    TextView mallPoints;
    @Bind(R.id.panicbuying_shifujia)
    TextView mpanicbuyingShifujia;
    @Bind(R.id.bottem)
    LinearLayout bottem;
    @Bind(R.id.qianggouwancheng)
    TextView qianggouwancheng;
//    @Bind(R.id.humiaojihua)
//    ImageView humiaojihua;


    //    3.观察者申明
    private Observable<String> rxBusDataObservable;
    private String customerid;
    private String ids;
    private String count;
    private List<JiFenInfo.DataBean> listFlag;
    private List<JiFenInfo.DataBean> list = new ArrayList<JiFenInfo.DataBean>();
    private JiFenAdapter adapter;
    private BigDecimal allPrice = new BigDecimal(0);
    private BigDecimal allpv = new BigDecimal(0);
    private BigDecimal allpoint = new BigDecimal(0);
    ;
    private float RealPay; //实付价
    private int num;
    private JiFenInfo panicbuyingInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jifen);
        ButterKnife.bind(this);
        initView();
        getPlusinfo();
    }

    private void initView() {

        customerid = SPUtils.get(this, "Id", "").toString();
//初始化
        new JiFenPresenter(this);
//加载数据
        mPresenter.getPanicBuyingInfo(customerid);

    }

    //获取返回值
    @Override
    public void showPanicBuyingInfo(String panicbuying) {
        Log.e("panicbuying", panicbuying);
        panicbuyingInfo = JSON.parseObject(panicbuying, JiFenInfo.class);
        if (panicbuyingInfo.isSuccess()) {


            list.addAll(panicbuyingInfo.getData());
            adapter = new JiFenAdapter(list, this);
            panicbuyingListview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            //限抢一次
            bottem.setVisibility(View.INVISIBLE);
            qianggouwancheng.setVisibility(View.VISIBLE);
            qianggouwancheng.setText("没有可兑换商品");
        }


    }

    @OnClick({R.id.panicbuying_shifujia, R.id.paincbuying_confirmpay_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.paincbuying_confirmpay_back:
                ActivityController.getInstance().removeActivity(this);
                finish();
                break;
            case R.id.panicbuying_shifujia:
                Log.e("aaa", String.valueOf(panicbuyingInfo.getBalance()));
                if (allpoint.compareTo(new BigDecimal(0)) != 1) {
                    Toast.makeText(this, "请选择商品", Toast.LENGTH_SHORT).show();
                    return;

                } else if (allpoint.compareTo(new BigDecimal(panicbuyingInfo.getBalance())) == 1) {
                    Toast.makeText(this, "对不起您的积分不够", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    for (int i = 0; i < listFlag.size(); i++) {
                        if (listFlag.get(i).getCount() == 0) {
                            listFlag.remove(i);
                        }
                    }
                    Intent toConfirmPay = new Intent(this, BonusPointsConfirmPayActivity.class);
                    toConfirmPay.putExtra("listFlag", (Serializable) listFlag);
                    toConfirmPay.putExtra("num", "" + num);
                    toConfirmPay.putExtra("allPrice", "" + allPrice);

                    toConfirmPay.putExtra("allpoints", "" + allpoint);
                    toConfirmPay.putExtra("ids", ids);
                    toConfirmPay.putExtra("count", count);
                    startActivity(toConfirmPay);
                }

                break;

        }
    }


    @Override
    public void setPresenter(JiFenContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.subscribe();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.unsubscribe();
    }

    // 4.rxbus的使用
    public void getPlusinfo() {
        rxBusDataObservable = RxBus.get().register("rxbus", String.class);
        rxBusDataObservable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(rxBusData -> {
                    plusPrice();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除订阅
        mPresenter.unsubscribe();
        RxBus.get().unregister("rxbus", rxBusDataObservable);
    }

    //计算总金额
    public void plusPrice() {
        allPrice = new BigDecimal(0);
        allpv = new BigDecimal(0);
        allpoint = new BigDecimal(0);
        num = 0;
        RealPay = 0f;
        boolean flag = true;
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        listFlag = new ArrayList<JiFenInfo.DataBean>();
        for (JiFenInfo.DataBean info : list) {
            if (info.flag) {
                allpv = allpv.add(new BigDecimal(info.getPv()).multiply(new BigDecimal(info.getCount())));
                allpoint = allpoint.add(new BigDecimal(info.getPoint()).multiply(new BigDecimal(info.getCount())));
                allPrice = allPrice.add(new BigDecimal(info.getPrice()).multiply(new BigDecimal(info.getCount())));
                if (info.getCount() != 0) {
                    stringBuffer.append(info.getId() + ",");
                    sbCount.append(info.getCount() + ",");
                }
                num++;
                listFlag.add(info);
            }
            if (sbCount.length() != 0) {
                ids = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                count = sbCount.toString().substring(0, sbCount.toString().length() - 1);
            }
            if (!info.flag)
                flag = false;
        }
        mAllPrice.setText(String.format("%.2f", allPrice) + "");
        panicbuyingNum.setText("共 " + num + " 种商品");
        mpanicbuyingShifujia.setText("结算（" + String.format("%.2f", allPrice) + ")");
        mallPoints.setText(String.format("%.2f", allpoint) + "");
    }
}
